package com.lz.ionicbase;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.lz.ionicbase.model.AppInfo;
import com.lz.ionicbase.model.SimpleBean;
import com.lz.ionicbase.utils.BaseUtil;
import com.lz.ionicbase.utils.Constant;
import com.lz.ionicbase.utils.DateUtils;
import com.lz.ionicbase.utils.SpUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class SuperAppException implements UncaughtExceptionHandler {

	private static final String TAG = "SuperAppException";
	private Context context;

	private UncaughtExceptionHandler defaultExceptionHandler;
	private static SuperAppException superAppException;

	private SuperAppException() {
	}

	public static SuperAppException getInstance() {
		if (superAppException == null) {
			superAppException = new SuperAppException();
		}
		return superAppException;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		/**
		 * 保存崩溃,用于应用重启。由于崩溃时，回退栈依然存在，此时如果有静态数据会发生连续崩溃。
		 * 解决方案：记录崩溃标记，在SuperApplication中以单实例方式启动栈底activity，清空回退栈。
		 */
		SpUtils.saveBoolean(context,SpUtils.KEY_APP_CRASHED,true);
		ex.printStackTrace();

		String baseUrl = SpUtils.getString(context, SpUtils.KEY_BASE_URL, "");
		if(!TextUtils.isEmpty(baseUrl)){
			String errorLog = genLog(ex);
      //TODO 异常提交
//			sendServer(errorLog, baseUrl);
		}

//		if (defaultExceptionHandler != null) {
			// 将异常抛出，则应用会弹出异常对话框.这里先注释掉
//			defaultExceptionHandler.uncaughtException( thread, exception );
//			for (Activity activity : BaseActivity.sAllActivity) {
//				activity.finish();
//			}
//		}

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			Log.e(TAG, "error : ", e);
		}
//		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(10);
	}

	private void sendServer(String errorLog, String baseUrl) {
		Log.e("SuperAppException","sendServer1");
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = telephonyManager.getDeviceId();

		final Map<String, String> param = new HashMap();
		param.put("uid", deviceId);
		param.put("msessage", BaseUtil.getBase64(errorLog));

		final String url = baseUrl + Constant.UP_LOGS;
		Log.e("SuperAppException","sendServer2");
//
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				try {
//					okhttp3.Response response = OkGo.post(url)
//							.tag(this)
//							.params(param)
//							.execute();
//
//					if(response.isSuccessful()){
//						SimpleBean resObj = new Gson().fromJson(response.body().string(), SimpleBean.class);
//						if(resObj.code ==100){
//							Log.e("SuperAppException","日志提交成功!");
//						}else {
//							Log.e("SuperAppException","日志提交异常!");
//						}
//					}else{
//						Log.e("SuperAppException","日志提交异常!");
//					}
//					System.exit(10);
//				} catch (IOException e) {
//					e.printStackTrace();
//					Log.e("SuperAppException","日志提交异常!");
//					System.exit(10);
//				}
//			}
//		}).start();

		OkGo.post(url)
                .tag(this)
				.params(param)
				.execute(new AbsCallback<SimpleBean>() {

					@Override
					public SimpleBean convertSuccess(Response response) throws Exception {
						SimpleBean resObj = new Gson().fromJson(response.body().string(), SimpleBean.class);
						return resObj;
					}

					@Override
					public void onSuccess(SimpleBean resObj, Call call, Response response) {
						if(resObj.code ==100){
							Log.e("SuperAppException","日志提交成功!");
						}else {
							Log.e("SuperAppException","日志提交异常!");
						}
					}

					@Override
					public void onError(Call call, Response response, Exception e) {
						super.onError(call, response, e);
						Log.e("SuperAppException","日志提交onError!");
					}

					@Override
					public void onCacheSuccess(SimpleBean simpleBean, Call call) {
					}

					@Override
					public void onAfter(SimpleBean simpleBean, Exception e) {
						super.onAfter(simpleBean, e);
//						System.exit(10);
					}
				})
		;
	}

	/**
	 * 生成错误日志
	 * @param ex
	 * @return
     */
	private String genLog(Throwable ex){
		StringWriter sw = new StringWriter();
		PrintWriter printWriter = new PrintWriter(sw);
		ex.printStackTrace(printWriter);

		AppInfo appInfo = AppInfo.getAppInfo(context);
		String  msg = sw.toString();

		String time = DateUtils.dateToString(new Date(),DateUtils.yyyy_MM_dd_t);

		StringBuilder sb = new StringBuilder(msg)
		.append("\n").append("device_name: ").append(appInfo.device_name)
		.append("\n").append("os_name: ").append(appInfo.os_name)
		.append("\n").append("os_version: ").append(appInfo.os_version)
		.append("\n").append("versionName: ").append(appInfo.versionName)
		.append("\n").append("versionCode: ").append(appInfo.versionCode)
		.append("\n").append("time: ").append(time)
		.append("\n")
		;
		String errorLog = sb.toString();
		Log.e("SuperAppException",errorLog);
		return sb.toString();
	}

	public void init(Context context) {
		this.context = context;
		defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

}
